/**
 * VUE 全局方法
 * Created by home on 2017-05-23.
 */
import axios from "axios";
import stringify from "qs/lib/stringify"
import {Message} from "element-ui";

/**
 * ajax请求
 * @param url 请求地址
 * @param method 请求类型 get post put delete
 * @param data 参数
 * @param success 正常回调
 * @param error 错误回调
 */
export function request(url, method, data, success, error) {
    let option = {
        baseURL: '/a/',
        url: url,
        method: method,
    };
    switch (method) {
        case 'get':
            option.params = data;
            break;
        case 'post':
            option.data = stringify(data);
            break;
        default:
            option.data = data;
            break
    }// 发起一个POST请求
    return axios.request(option).then(res => {
        res.data.code = parseInt(res.data.code);
        switch (res.data.code) {
            case 1:
                success(res.data.data);
                return;
            //未登录
            case 10001:
            case 10004:
                window.location.href = './#/login';
                Message.error(res.data.msg);
                return;
            case 10003:
            case 10006:
            case 10007:
            case 10008:
            case 0:
                Message.error(res.data.msg);
                break;
        }
        typeof error == "function" && error(res.data);
    }).catch(errMsg => {
        Message.error('服务或网络异常');
    });
}
